package com.webtest.controller;

import com.baomidou.mybatisplus.annotation.TableField;
import com.github.pagehelper.PageInfo;
import com.webtest.dao.BookMapper;
import com.webtest.dao.BookShelfMapper;
import com.webtest.dao.BorrowMapper;
import com.webtest.dao.CommentMapper;
import com.webtest.entity.*;
import com.webtest.service.BookService;
import com.webtest.service.CommentService;
import com.webtest.service.ReturnService;
import com.webtest.service.admin.AdminUserService;
import com.webtest.vo.SearchBooks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private ReturnService returnService;
    @Autowired
    private BookService bookService;
    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private BookShelfMapper bookShelfMapper;

    @RequestMapping("/tocomments/{bookId}")
    public String toComments(@PathVariable("bookId") Integer bookId, Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        User userById = adminUserService.getUserById(user.getId());
        model.addAttribute("userById", userById);
        model.addAttribute("bookId", bookId);
        List<Comment> comments = commentService.listComment(bookId);
        model.addAttribute("comments", comments);
        return "comment";
    }

    @PostMapping("/comments")
    @Transactional
    public String post(Comment comment, HttpSession session) {
        User user = (User) session.getAttribute("user");
        User userById = adminUserService.getUserById(user.getId());

        commentService.saveComment(comment);
        // 更新金额
        Borrow borrow1 = new Borrow();
        borrow1.setBookId(comment.getBookId());
        borrow1.setStuId(userById.getId());
        borrow1.setStatus(1);
        List<Borrow> borrows = borrowMapper.selectBorrowList(borrow1);
        Borrow borrowInfo = borrows.get(0);
        //删除借阅信息
        returnService.deleteBorrow(comment.getBookId(), userById.getId());

        // 更新书架
        Book book = bookService.findBookById(comment.getBookId());
        SearchBooks book1 = new SearchBooks();
        book1.setBookId(comment.getBookId());
        book1.setShelfId(Long.valueOf(comment.getSelectedShelf()));
        List<BookShelf> bookShelfs = bookShelfMapper.getBookShelf(book1);
        if (bookShelfs.size() > 0){
            BookShelf bookShelf = bookShelfs.get(0);
            bookShelf.setCount(bookShelf.getCount() + 1);
            bookShelfMapper.updateBookShelfByCount(bookShelf);
        }  else {
            BookShelf bookShelf = new BookShelf();
            bookShelf.setBookId(comment.getBookId());
            bookShelf.setCount(1);
            bookShelf.setShelfId(Long.valueOf(comment.getSelectedShelf()));
            bookShelfMapper.addBookShelf(bookShelf);
        }

        Date borrowDate = borrowInfo.getBorrowDate();
        long diff = new Date().getTime() - borrowDate.getTime();
        int borrowDay = (int) (diff / (24 * 60 * 60 * 1000));
        double v = borrowDay * book.getPrice();
        Integer vip = user.getVip();
        if (vip > 0) v = v * 0.9;
        user.setMoney(user.getMoney() - v);
        adminUserService.updateUser(user);
        borrow1.setDamages(v);
        borrow1.setStatus(2);
        borrowMapper.updateBorrow(borrow1);
        //评分统计
        List<Comment> comments = commentMapper.selectAll();
        Map<Integer, List<Comment>> map = new HashMap<>();

        for (Comment one : comments) {
            if (map.get(one.getBookId()) == null) {
                map.put(one.getBookId(), new ArrayList<>());
            }
            map.get(one.getBookId()).add(one);
        }
        // 更新库存
        for (Map.Entry<Integer, List<Comment>> one : map.entrySet()) {
            Book book2 = new Book();
            double count = 0;
            double size = 0;
            for (Comment comment1 : one.getValue()) {
                count += comment1.getScore();
                size++;
            }
            book2.setId(one.getKey());
            book2.setGood(count / size);
            bookMapper.updateGoodById(book2);
        }

        return "redirect:/borrow/";
    }

    //删除评论
    @GetMapping("/comment/{id}/{bookId}/delete")
    public String delete(@PathVariable Long id, @PathVariable Integer bookId, Comment comment, RedirectAttributes attributes, HttpSession session) {
        commentService.deleteComment(id);
        User user = (User) session.getAttribute("user");
        User userById = adminUserService.getUserById(user.getId());
        attributes.addFlashAttribute("userById", userById);
//        List<Comment> comments = commentService.listComment();
//        attributes.addFlashAttribute("comments", comments);
        return "redirect:/tocomments/" + bookId;
    }
}
